package com.lyloou.practice.dp.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;

/**
 * @author lyloou
 * @date 2020/05/29
 * @desc
 */
public class ProxyFactory {

    public static Object getJdkProxy(Object o) {
        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return doMethod(o, method, args);
            }
        });
    }

    public static Object getCglibProxy(Object target) {
        return Enhancer.create(target.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                return doMethod(target, method, args);
            }
        });
    }

    private static Object doMethod(Object o, Method method, Object[] args) throws SQLException, IllegalAccessException, InvocationTargetException {
        System.out.println("before");
        Object result = method.invoke(o, args);
        System.out.println("after");
        return result;
    }

}
